﻿using orderCreater.ben;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace orderCreater
{
    public partial class Form2 : Form
    {
        [DllImport("User32.dll")]
        private static extern bool SetCursorPos(int x, int y);
        [DllImport("User32.dll")]
        private static extern void mouse_event(MouseEventFlag flags, int dx, int dy, uint data, UIntPtr extraInfo);
        public Form2()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.sr_bgw.WorkerSupportsCancellation = true;
            this.webBrowser1.Navigate("www.alipay.com");
            //richTextBox1.BackColor = Color.Transparent;
        }
        public struct POINT
        {
            public int X;
            public int Y;
        }
        public enum MouseEventFlag
        {
            Move = 0x0001, //移动鼠标
            LeftDown = 0x0002,//模拟鼠标左键按下
            LeftUp = 0x0004,//模拟鼠标左键抬起
            RightDown = 0x0008,//鼠标右键按下
            RightUp = 0x0010,//鼠标右键抬起
            MiddleDown = 0x0020,//鼠标中键按下 
            MiddleUp = 0x0040,//中键抬起
            XDown = 0x0080,
            XUp = 0x0100,
            Wheel = 0x0800,
            VirtualDesk = 0x4000,
            Absolute = 0x8000//标示是否采用绝对坐标
        }
        public Point GetOffset(HtmlElement el)
        {
            //get element pos
            Point pos = new Point(el.OffsetRectangle.Left, el.OffsetRectangle.Top);

            //get the parents pos
            HtmlElement tempEl = el.OffsetParent;
            while (tempEl != null)
            {
                pos.X += tempEl.OffsetRectangle.Left;
                pos.Y += tempEl.OffsetRectangle.Top;
                tempEl = tempEl.OffsetParent;
            }

            return pos;
        }
        POINT mc = new POINT();
        int pagenum = 0, page_i = 0, detail_i = 0;
        FormDetail frmDetail;
        private void button1_Click(object sender, EventArgs e)
        {
            frmDetail = new FormDetail();
            foreach (HtmlElement a in webBrowser1.Document.GetElementsByTagName("a"))
            {
                if (a.GetAttribute("className").IndexOf("page-end") >= 0)
                {
                    var a_pagenum = a.GetAttribute("pagenum");
                    LogHelper.Debug(a_pagenum);
                  
                    try { pagenum = Convert.ToInt16(a_pagenum); timer2.Enabled = true; } catch { pagenum = 0; }

                }
            }
            button1.Enabled = false;
        }
        private bool hh()
        {
            mc.X = Convert.ToInt16(tbX.Text); mc.Y = Convert.ToInt16(tbY.Text);
            SetCursorPos(mc.X, mc.Y);
            webBrowser1.Document.Window.ScrollTo(0, webBrowser1.Document.Body.ScrollRectangle.Height);
            HtmlElement ElementTable = webBrowser1.Document.GetElementById("tradeRecordsIndex");
            foreach (HtmlElement ElementBody in ElementTable.GetElementsByTagName("tbody"))
            {
                foreach (HtmlElement tr in ElementBody.GetElementsByTagName("tr"))
                {
                    var m_str = "";
                    foreach (HtmlElement td in tr.GetElementsByTagName("td"))
                    {
                        if (td.GetAttribute("className") == "time")
                        {
                            foreach (HtmlElement p1 in td.GetElementsByTagName("p"))
                            {
                                if (p1.InnerText == "今天")
                                {
                                    m_str += DateTime.Now.ToString("yyyy-MM-dd");
                                }
                                else if (p1.InnerText == "昨天")
                                {
                                    m_str += DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
                                }
                                else
                                {
                                    m_str += p1.InnerText;
                                }
                                if (p1.GetAttribute("className") == "text-muted")
                                {
                                    m_str += "\t";
                                }
                            }
                        }
                        if (td.GetAttribute("className") == "name")
                        {
                            foreach (HtmlElement p1 in td.GetElementsByTagName("p"))
                            {
                                if (p1.GetAttribute("className") == "consume-title")
                                {
                                    foreach (HtmlElement a in p1.GetElementsByTagName("p"))
                                        m_str += a.InnerText + "\t";
                                }
                                if (p1.GetAttribute("className").IndexOf("name") >= 0)
                                {
                                    m_str += p1.InnerText;
                                }
                            }
                            foreach (HtmlElement div in td.GetElementsByTagName("div"))
                            {
                                if (div.GetAttribute("className").IndexOf("tradeNo") >= 0)
                                {
                                    foreach (HtmlElement a in div.GetElementsByTagName("a"))
                                    {
                                        m_str += a.GetAttribute("title") + "\t";
                                    }
                                }
                            }
                        }

                        if (td.GetAttribute("className") == "amount")
                        {
                            foreach (HtmlElement span in td.GetElementsByTagName("span"))
                            {
                                m_str += span.InnerText + "\t";
                            }
                        }

                        if (td.GetAttribute("className") == "amount")
                        {
                            foreach (HtmlElement a in td.GetElementsByTagName("a"))
                            {
                                m_str += "交易明显:" + a.GetAttribute("href") + "\t";
                            }
                        }
                        if (td.GetAttribute("className") == "status")
                        {
                            foreach (HtmlElement p1 in td.GetElementsByTagName("p"))
                            {
                                if (p1.GetAttribute("className") == "text-muted")
                                {
                                   if(p1.InnerText != null) m_str += "交易状态:" + p1.InnerText + "\t";
                                }
                            }
                        }
                        if (td.GetAttribute("className") == "operation")
                        {
                            foreach (HtmlElement li in td.GetElementsByTagName("li"))
                            {
                                if (li.GetAttribute("seed") == "trade-detail")
                                {
                                    listBox1.Items.Add(li.GetAttribute("data-link"));
                                    //webBrowser2.Navigate(li.GetAttribute("data-link"));
                                }
                            }
                        }
                        
                    }
                    LogHelper.Debug(m_str);
                }
            }
            
            return false;
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格键
            if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //处理负数
            if (e.KeyChar > 0x20)
            {
                try
                {
                    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
                }
                catch
                {
                    e.KeyChar = (char)0;   //处理非法字符
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (page_i < pagenum)
            {
                hh();
                //mouse_event(MouseEventFlag.Move, mc.X, mc.Y, 0, UIntPtr.Zero);
                //System.Threading.Thread.Sleep(1000);
                mouse_event(MouseEventFlag.LeftDown, mc.X, mc.Y, 0, UIntPtr.Zero);
                mouse_event(MouseEventFlag.LeftUp, mc.X, mc.Y, 0, UIntPtr.Zero);
                LogHelper.Debug("AutoClick");
                page_i++;
                timer1.Enabled = false;
                timer2.Enabled = true;
            }
            else {
                timer1.Enabled = false;
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(listBox1.Items[listBox1.SelectedIndex].ToString());
            //webBrowser2.Navigate(listBox1.Items[listBox1.SelectedIndex].ToString());
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if (detail_i < listBox1.Items.Count)
            {
                frmDetail.Show();
                frmDetail.SetWebBrowserUrl(@"https://lab.alipay.com/consume/queryTradeDetail.htm?tradeNo="+listBox1.Items[detail_i].ToString());         
                detail_i++;
            }
            else
            {
                timer2.Enabled = false;
            }
        }

        private void sr_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            
        }
        /// <summary>  
        /// 根据Url获取页面所有内容  
        /// </summary>  
        /// <param name="URL">请求的url</param>  
        /// <returns>返回页面的内容</returns>  
        public string GetContentFromUrl(string URL)
        {
            try
            {
                string strBuff = "";
                int byteRead = 0;
                char[] cbuffer = new char[256];
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(URL));
                HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
                Stream respStream = httpResp.GetResponseStream();
                StreamReader respStreamReader = new StreamReader(respStream, System.Text.Encoding.UTF8);
                byteRead = respStreamReader.Read(cbuffer, 0, 256);
                while (byteRead != 0)
                {
                    string strResp = new string(cbuffer, 0, byteRead);
                    strBuff = strBuff + strResp;
                    byteRead = respStreamReader.Read(cbuffer, 0, 256);
                }
                respStream.Close();
                return strBuff;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>  
        /// 根据Url获取页面所有内容  
        /// </summary>  
        /// <param name="url">请求的url</param>  
        /// <returns>返回页面的内容</returns>  
        public string GetContentFromUrl2(string url)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;//获取或设置请求凭据  
                Byte[] pageData = client.DownloadData(url); //下载数据  
                string pageHtml = System.Text.Encoding.Default.GetString(pageData);
                return pageHtml;
            }
            catch (WebException ex)
            {
                return ex.Message;
            }
        }
    }
}
